package com.jhs.kjs.handler;

import java.util.Iterator;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.DispatcherServlet;
import org.springframework.web.servlet.HandlerExecutionChain;
import org.springframework.web.util.UrlPathHelper;

public class SDispatcher extends DispatcherServlet {
	private static final Logger logger = LoggerFactory
			.getLogger(SDispatcher.class);
	
	private static UrlPathHelper urlPathHelper = new UrlPathHelper();
	/**
	 * 
	 */
	private static final long serialVersionUID = -8956179558444962005L;

	@Override
	protected void doDispatch(HttpServletRequest req, HttpServletResponse rep)
			throws Exception {

			if("appServlet".equals(getServletName())){
				String requestUri = urlPathHelper.getRequestUri(req);
				
				StringBuilder sb = new StringBuilder("\n\n================================================\n");
				HandlerExecutionChain mappedHandler = getHandler(req);
				try{
					String className = mappedHandler.getHandler().toString();
					className = className.substring(className.indexOf("com.jhs.kjs."));
					sb.append(parseClassName(className)).append("\n");
				}catch(Exception e){}
				
				String[] parse = requestUri.split("[.]");
				
				if(parse.length==1||"json".equals(parse[1].toLowerCase())){
					sb.append("uri : ").append(requestUri).append("\n----------------------------\n");
					
					
					String key="";
					Iterator it = req.getParameterMap().keySet().iterator();
					while(it.hasNext()){
						key = it.next().toString();
						sb.append("key [").append(key).append("]");
						sb.append(" : value = ").append(req.getParameter(key).toString()).append("\n");
					}
					sb.append("================================================\n");
					logger.debug(sb.toString());
				}
			}
		super.doDispatch(req, rep);
	}

	private String parseClassName(String ori){
		StringBuilder sb = new StringBuilder();
		String[] classArr = ori.substring(0, ori.indexOf("(")).split("[.]");
		int arrLength = classArr.length-1;
		String methodName = classArr[arrLength]; 
		String className = (String) ori.subSequence(0, ori.indexOf("."+methodName));
		sb.append("Class = ").append(className).append("\n");
		sb.append("method = ").append(methodName).append("\n");
		
		
		return sb.toString();
	}
}

